package com.developer.platform.infrastructure.client;

import com.veeker.core.enums.SystemErrorType;
import com.veeker.core.exceptions.BusinessException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2020-12-29
 */
@Component
public class DingDingSign {

  public String url(String url, String secret){
    try{
      Long timestamp = System.currentTimeMillis();
      return url+"&timestamp="+timestamp+"&sign="+this.sign(secret, timestamp);
    }catch (Exception e){
      BusinessException.isTrue(true, SystemErrorType.SYSTEM_ERROR);
    }
    return url;
  }

  private String sign(String secret, Long timestamp)
      throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    String stringToSign = timestamp + "\n" + secret;
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
    return URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
  }

}
